<?php
	/**
    *  Forums
    *  author: Brian Thorne
    *  date: 6/5/08
    */

    $content = '';
    if ($_SESSION['logged']) 
	{
        include('data/lib_components.inc.php');
        include('data/lib_f_admin.inc.php');
        include('data/lib_f_pictures.inc.php');
        include('data/class.mailer.php'); 
    }
    if ($_GET['EID'])
	{
        $EID = $_GET['EID'];
    }
	if ($_GET['TID'])
	{
        $TID = $_GET['TID'];
    }
    
    /* A new post or an existing post has been edited or created. */
    if ($_POST['submitted']) 
	{
        include('data/lib_f_validate.inc.php');
        extract($_POST);
        
        if (!$Title = validateText($Title)) $err .= 'Title invalid.<br>';
        if (!$Text = validateText($Text)) $err .= 'Text invalid.<br>';
       
        $Time = $Time ? "'$Time'":'NULL';
        
        if (!$err) 
		{
            if ($EID) {
                mq("UPDATE board SET Title='$Title',Text='$Text',Date='$Date',Time=$Time WHERE EID=".$EID);
                $action = 'Updated ';
            } else {
				if(!$TID)
				{
                    // New thread
					$TID = mqs("SELECT COUNT(TID) FROM board") + 1;
                    while($TID == mqs("SELECT TID FROM board where TID=".$TID))
                    {
                        $TID+=1;
                    } 
					
				}
				$EID = mq("INSERT INTO board (Title,Text,Date,Time,MID,Type,TID) VALUES ('$Title','$Text','$Date',$Time,'".$_SESSION['MID']."',".$db_types[$_SESSION['subtopic']].",".$TID.")");
                $mailer->mailPost($EID);
                
				$action = 'Created ';
            }
            logevent("$action \'$Title\' ($EID)");
            $EID=null;
        } else $content .= $err;
    
	/**
    * Delete an entire thread
    */
    } else if ($_GET['deletethread']) 
	{
        if ($d = mqs("SELECT MID,Title,Type, EID FROM board WHERE TID=".($_GET['deletethread']+0))) 
		{
           	$query = "DELETE FROM `board` WHERE `TID` =".($_GET['deletethread']+0) ;//." LIMIT ".mqs("SELECT COUNT(*) FROM `board` WHERE TID=".($_GET['deletethread']+0))+0;
			if($res = mq($query))
			{
				logevent("Board entry \'".$d['Title']."\' deleted.");
				$content .= "Board entry \'".$d['Title']."\' deleted.";
			} else { 
				logevent("Deletion error: <br>An error occured with the query: " .$query . "<br>Result from query was: " .$res); 
			}
        }
    }

	/**
    * Delete a post in a thread
    */
    else if ($_GET['deletepost']) 
	{
        if ($d = mqs("SELECT MID,Title,Type, TID FROM board WHERE EID=".($_GET['deletepost']+0))) 
		{
           	$query = "DELETE FROM `board` WHERE `EID` =".($_GET['deletepost']+0) ;//." LIMIT ".mqs("SELECT COUNT(*) FROM `board` WHERE EID=".($_GET['deletepost']+0))+0;
			if($res = mq($query))
			{
				logevent("Board entry \'".$d['Title']."\' deleted.");
				$content .= "Board entry \'".$d['Title']."\' deleted.";
			} else { 
				logevent("Deletion error: <br>An error occured with the query: " .$query . "<br>Result from query was: " .$res); 
			}
        }
    }


  
  /**
  *  Display a thread based on a topic (TID) with individual posts (EID) each by a member (MID)
  *  Want each user to be able to edit/delete own posts/replys.
  *	 Want anyone logged in to be able to reply to any topic.
  *  Any webmaster/commitee member can delete another persons posts or entire topic. 
  */
	
	if ($_GET['TID'] || $newthread = $_GET['newthread'])
	{
	$TID = $_GET['TID'];//get topic id.
	if($posts = mq("SELECT EID,Date,Time,Title,Text,Name,Pic FROM board b
					   INNER JOIN members m ON m.MID=b.MID
					   WHERE TID=".($TID+0)." ORDER BY EID"))
	{
		$num_posts = mysql_num_rows($posts);
		$post = mysql_fetch_assoc($posts);
		extract($post);
		$content .= '<br/><h2>Topic: '.$Title.'</h2><table style="width:100%" cellpadding="3"><td><a href="'.$_SERVER['PHP_SELF'].'?topic=board&subtopic='.$_SESSION['subtopic'].'" title="Back to overview">Back to overview</a><br>Posts: '.$num_posts.'</td><td>Thread creater: '.$Name.'</td><td> </td></table>';
	}
	
	/* 
	 * This loop shows each post. And creates a reply to thread form at the bottom 
	 * Remember post 1's data is allready extarcted, last post has no data on purpose.
	*/
	$num_sections = $num_posts;
	if($_SESSION['logged']) $num_sections +=1;
	for($post=1; $post<=$num_sections;$post++ )
	{
		$content .= '<hr />Post: ' . $post;
		
		if($post == $num_posts+1)
		{
			//All posts complete, don't want to try access db!
			$content .= ($_GET['newthread'] ? "" :"<h3>Reply to Thread</h3>");
			$newentry = true;
			$Title=null;$Date=0;$Time=0;$Name=null;$Text=null;$EID=null;
		} elseif($post == 1) 
		{
			//First post contains Thread details, is allready extarcted
			// So do a whole lota nothing...
		} else {
			//Need to get the next post from the DB result $posts
			$entry = mysql_fetch_assoc($posts);
			extract($entry);
		}
			# Check if user may edit or only look at this post.
			$edit = $_SESSION['logged'] && ($_GET['newthread'] || (($newentry && $post==1+$num_posts) || ($_SESSION['rights'] & $r_webmaster) || mqs("SELECT MID FROM board WHERE EID=".($EID+0)) == $_SESSION['MID']));
		 $content .= $edit ? ' '. ($EID ? '<a href="'.$_SERVER['PHP_SELF'].'?topic=board&deletepost='.$EID .'" onclick="return confirm(\'Delete post &quot;'.$Title.'&quot;?\n This cannot be undone!\')">
								<img src="'.BILDERDIR.'del.gif" alt="del">
							</a>':'') .'<form action="'.$_SERVER['PHP_SELF'].'" method="POST">':'';
		 $content .= '<table style="width:100%" cellpadding="3">
						<tr>'.($edit ? '
							<td colspan="2"><input type="text" size="63" name="Title" value="'.DBToForm($Title).'" class="text"></td></tr>
							<td>'.DatePicker('Date',$Date).'</td><td>'.TimePicker('Time',$Time,true).'</td></tr>':
							'<td><b>'.$Title.'</b></td><td style="text-align:right">'.formatDate($Date).' '.formatTime($Time).'</td></tr>').'</tr>
						<tr><td colspan="2" style="text-align:right">'.($_GET['newentry'] ? $_SESSION['username']: $Name) .'<br></td></tr>
						<tr><td colspan="2">'. ($Pic ? '<img class="avatar" src="./pics/members/'.$Pic.'" width="150" title="'.$Name.'" alt="'.$Name.'" >':"").($edit ? '<textarea name="Text" rows="10" cols="64">'.DBToForm($Text).'</textarea>':$Text).'</td></tr>
						'.($edit ? '<tr><td colspan="2">
						'.($EID ?'<input type="hidden" name="EID" value="'.$EID.'">':'').'
						<input type="hidden" name="TID" value="'.$TID.'">
						<input type="hidden" name="submitted" value="1">
						<input type="submit" class="button" value="Submit"></td></tr>':'').'
					</table>';
		 $content .= $edit ? '</form>':'';
		 
	}$content .= ($num_posts > 1)? '<a href="'.$_SERVER['PHP_SELF'].'" title="Back to overview">Back to overview</a>':'';
  /**
  * Display list of Threads
  * 
  */
  } else {
    if ($_SESSION['logged']) 
	{
		$content = '<a href="'.$_SERVER['PHP_SELF'].'?newthread=1">Create new thread</a><br>';
    }
    if ($res = mq("SELECT b1.TID,b1.EID,b1.Title,m.Name,m.MID 
                    FROM board AS b1
                    INNER JOIN members m ON m.MID=b1.MID
                    WHERE Type=".$db_types[$_SESSION['subtopic']]." AND b1.EID = (SELECT MIN(EID) AS meid FROM board as b2 WHERE b1.TID = b2.TID )
                    GROUP BY TID 
                    ORDER BY Date DESC,Time"))  /* SELECT TID,Date,Title,Name,m.MID FROM board b
                    INNER JOIN members m ON m.MID=b.MID
                    WHERE Type=".$db_types[$_SESSION['subtopic']]." GROUP BY TID ORDER BY Date DESC,Time*/
	{
        $content .= '<table cellpadding="3"><tr>
                       '.($_SESSION['logged'] ? '<th>Del</th>':'').'
                       <th>Date</th><th>Title</th><th>From</th><th>Replys</th></tr>';
         
        while($data = mysql_fetch_array($res)) 
		{
            $content .= '<tr>
                           '.($_SESSION['logged'] ? '<td>'.($_SESSION['rights'] & $r_webmaster || $_SESSION['MID'] == $data['MID'] 
                                  ? '<a href="'.$_SERVER['PHP_SELF'].'?deletethread='.$data['TID'].'" onclick="return confirm(\'Delete entire thread &quot;'.$data['Title'].'&quot; which has '.mqs('SELECT COUNT(*) from `board` WHERE TID = '.$data['TID']).' posts?\nThis cannot be undone!\')">
                                       <img src="'.BILDERDIR.'del.gif" alt="del">
                                     </a>'
                                  :'').'</td>' : '').'
							<td>'.formatDate($data['Date']).'</td>
							<td><a href="'.$_SERVER['PHP_SELF'].'?TID='.$data['TID'].'" title="'.$data['Title'].'">'.$data['Title'].'</a></td>
							<td>'.$data['Name'].'</td>
							<td>'.(int)(mqs('SELECT COUNT(*) from `board` WHERE TID = '.$data['TID'])-1) .'</td>
                        </tr>';
        }
        $content .= '</table>';               
    } else $content .= "no entries yet.";
} 
  
?>